/**
 * 日期选择组件
 * add by lifenping
 * on 20200229
 */
import React from 'react';
import moment from 'moment';
import { Form, DatePicker } from 'antd';

const { RangePicker } = DatePicker;

const FormItem = Form.Item;

interface ShowTime {
  format?: string;
}

interface PropsType {
  showTime?: ShowTime;
  label: string;
  name: string;
  initialValue?: string;
  rules?: [];
  itemLayout?: {};
  format?: string;
  getFieldDecorator?: any;
  getPopupContainer?: any;
  colon?: any;
  placeholder?: string;
  type?: string;
  style?:any;
  disabled?:any;
}

const DateItem: React.FC<PropsType> = props => {
  const {
    disabled,
    showTime,
    label,
    name,
    initialValue,
    rules,
    itemLayout,
    format = 'YYYY-MM-DD',
    getFieldDecorator,
    getPopupContainer,
    colon,
    type = 'DatePicker',
    ...othersProps
  } = props;

  const options = {
    getValueFromEvent: (date, dateString) => date,
    rules,
  };

  // 处理初始时间, 转成 moment object
  let initValue;
  if(initialValue){
    if (type === 'range') {
      initValue = [moment(initialValue[0], format), moment(initialValue[1], format)];
    } else {
      initValue = moment(initialValue, format);
    }
    options.initialValue = initValue;
  }

  return (
    <FormItem label={label} colon={colon} {...itemLayout} hasFeedback={!!rules}>
      {getFieldDecorator(
        name,
        options,
      )(
        type === 'range' ? (
          <RangePicker {...othersProps} disabled={disabled} getCalendarContainer={getPopupContainer} />
        ) : (
          <DatePicker {...othersProps} disabled={disabled} getCalendarContainer={getPopupContainer} />
        ),
      )}
    </FormItem>
  );
};

export default DateItem;
